{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-09-01T03:54:56.844472Z",
     "start_time": "2024-09-01T03:54:55.101971Z"
    }
   },
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "from d2l import torch as d2l\n",
    "\n",
    "# 首先加载数据集\n",
    "batch_size, num_steps = 32, 35\n",
    "train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T03:57:04.465813Z",
     "start_time": "2024-09-01T03:57:04.450561Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 初始化模型参数\n",
    "def get_lstm_params(vocab_size, num_hiddens, device):\n",
    "    num_inputs = num_outputs = vocab_size\n",
    "\n",
    "    def normal(shape):\n",
    "        return torch.randn(size=shape, device=device) * 0.01\n",
    "\n",
    "    # 统一赋值，仅仅为了方便\n",
    "    def three():\n",
    "        return (normal((num_inputs, num_hiddens)),\n",
    "                normal((num_hiddens, num_hiddens)),\n",
    "                torch.zeros(num_hiddens, device=device))\n",
    "\n",
    "    W_xi, W_hi, b_i = three()  # 输入门参数\n",
    "    W_xf, W_hf, b_f = three()  # 遗忘门参数\n",
    "    W_xo, W_ho, b_o = three()  # 输出门参数\n",
    "    W_xc, W_hc, b_c = three()  # 候选记忆元参数\n",
    "\n",
    "    # 输出层参数\n",
    "    W_hq = normal((num_hiddens, num_outputs))\n",
    "    b_q = torch.zeros(num_outputs, device=device)\n",
    "\n",
    "    # 附加梯度\n",
    "    params = [W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc, b_c, W_hq, b_q]\n",
    "    for param in params:\n",
    "        param.requires_grad_(True)\n",
    "    return params"
   ],
   "id": "fc5cd4c500f0855e",
   "execution_count": 2,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T03:59:17.927294Z",
     "start_time": "2024-09-01T03:59:17.917565Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 初始化函数，初始H和C\n",
    "def init_lstm_state(batch_size, num_hiddens, device):\n",
    "    return (torch.zeros((batch_size, num_hiddens), device=device),\n",
    "            torch.zeros((batch_size, num_hiddens), device=device))"
   ],
   "id": "f8582338f376d749",
   "execution_count": 3,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T04:02:06.171519Z",
     "start_time": "2024-09-01T04:02:06.164326Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 实际模型\n",
    "def lstm(inputs, state, params):\n",
    "    [W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc, b_c, W_hq, b_q] = params\n",
    "    (H, C) = state\n",
    "\n",
    "    outputs = []\n",
    "\n",
    "    for X in inputs:\n",
    "        I = torch.sigmoid((X @ W_xi) + (H @ W_hi) + b_i)\n",
    "        F = torch.sigmoid((X @ W_xf) + (H @ W_hf) + b_f)\n",
    "        O = torch.sigmoid((X @ W_xo) + (H @ W_ho) + b_o)\n",
    "        C_tilda = torch.tanh((X @ W_xc) + (H @ W_hc) + b_c)\n",
    "        C = F * C + I * C_tilda\n",
    "        H = O * torch.tanh(C)\n",
    "        Y = (H @ W_hq) + b_q\n",
    "\n",
    "        outputs.append(Y)\n",
    "\n",
    "    return torch.cat(outputs, dim=0), (H, C)"
   ],
   "id": "aed1763d841f66c5",
   "execution_count": 4,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 训练和预测\n",
    "vocab_size, num_hiddens, device = len(vocab), 256, d2l.try_gpu()\n",
    "num_epochs, lr = 500, 1\n",
    "model = d2l.RNNModelScratch(len(vocab), num_hiddens, device, get_lstm_params, init_lstm_state, lstm)\n",
    "d2l.train_ch8(model, train_iter, vocab, lr, num_epochs, device)"
   ],
   "id": "543e3a3661796f17",
   "execution_count": 5,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 简洁实现\n",
    "num_inputs = vocab_size\n",
    "lstm_layer = nn.LSTM(num_inputs, num_hiddens)\n",
    "model = d2l.RNNModel(lstm_layer, len(vocab))\n",
    "model = model.to(device)\n",
    "d2l.train_ch8(model, train_iter, vocab, lr, num_epochs, device)"
   ],
   "id": "1af125d06c77e673",
   "execution_count": 6,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
